package com.jxd.ordering.handle;

        import com.jxd.ordering.annotation.CheckPermission;
        import com.jxd.ordering.exception.serviceexception.TokenException;
        import com.jxd.ordering.service.IUserService;
        import com.jxd.ordering.util.JwtUtil;
        import com.jxd.ordering.util.PermissionUtil;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Component;
        import org.springframework.web.method.HandlerMethod;
        import org.springframework.web.servlet.HandlerInterceptor;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import java.lang.reflect.Method;

/**
 * @ClassName GlobalInterceptor
 * @Description TODO
 * @Author Ankailong
 * @Date 2022/9/29
 * @Version 1.0
 */

@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录鉴权
        String token = request.getHeader("token");
        if ("".equals(token) || token == null) {
            throw new TokenException("token为空");
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        String permission = "";

        // 校验token
        try {
            String userid = JwtUtil.parseToken(token);
            permission = userService.getPermissionByUserid(Integer.parseInt(userid));
            request.setAttribute("userid", userid);
            request.setAttribute("permission", permission);
        }catch (Exception e){
            throw new TokenException("token异常");
        }

        //校验权限等级
        if (method.isAnnotationPresent(CheckPermission.class)) {
            CheckPermission annotation = method.getAnnotation(CheckPermission.class);
            PermissionUtil.PermissionControl(permission, Integer.parseInt(annotation.value()));
        }
        return true;
    }
}
